package com.xs.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xs.common.R;
import com.xs.domain.Consumer;
import com.xs.domain.dto.ConsumerDTO;
import com.xs.mapper.ConsumerMapper;
import com.xs.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 徐双
 * @ClassName ConsumerController
 * @date 2023-01-02 16:12
 * @Description:
 * @Version:1.0
 */

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private ConsumerMapper consumerMapper;

    /**
     * 登录
     *
     * @param adminRequest
     * @return
     */
    @PostMapping("/login")
    public R loginStatus(@RequestBody ConsumerDTO adminRequest) {
        return consumerService.verityPasswd(adminRequest);
    }

    /**
     * 注册
     *
     * @param registryRequest
     * @return
     */
    @PostMapping("/add")
    public R addUser(@RequestBody ConsumerDTO registryRequest) {
        return consumerService.addUser(registryRequest);
    }

    /**
     * 更新密码
     *
     * @param updatePasswordRequest
     * @return
     */
    @PostMapping("/updatePassword")
    public R updatePassword(@RequestBody ConsumerDTO updatePasswordRequest) {
        return consumerService.updatePassword(updatePasswordRequest);
    }

    /**
     * 分页查询全部用户
     *
     * @return
     */
    @GetMapping("/page")
    public R findUserAll(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(defaultValue = "") String username) {
        return consumerService.findPage(pageNum, pageSize, username);
    }

    /**
     * 返回所有用户
     *
     * @return
     */
    @GetMapping("/userAll")
    public R allUser() {
        return consumerService.allUser();
    }

    /**
     * 返回指定 ID 的用户
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public R userOfId(@RequestParam int id) {
        return consumerService.userOfId(id);
    }

    /**
     * 更新用户信息
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    public R updateUserMsg(@RequestBody ConsumerDTO updateRequest) {
        return consumerService.updateUserMsg(updateRequest);
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public R deleteUser(@RequestParam int id) {
        return consumerService.deleteUser(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/delBatch")
    public R deleteBathIds(@RequestBody List<Integer> ids) {
        return consumerService.deleteBathIds(ids);
    }

    /**
     * 导出数据
     *
     * @param response
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //从数据库查询出所以的数据
        List<Consumer> list = consumerService.list();
        //在内存操纵，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);
        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file, @RequestParam("id") Integer id) throws IOException {
        //获取文件原名
        String originalFilename = file.getOriginalFilename();
        //获取文件类型，即后缀名
        String type = FileUtil.extName(originalFilename);
        //先存储到磁盘
        File uploadParentFile = new File(fileUploadPath);
        //判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        //文件标识位
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        String url;
        //上传文件到磁盘
        file.transferTo(uploadFile);
        //获取文件的md5
        String md5 = SecureUtil.md5(uploadFile);
        //从数据库查询是否存在相同的记录
        Consumer dbFiles = getFileByMd5(md5);
        if (dbFiles != null) {
            url = dbFiles.getAvatar();
            //由于文件已存在，所以删除刚才上传的重复文件
            uploadFile.delete();
        } else {
            //数据若不存在重复文件，则不删除刚才上传的文件
            url = "http://localhost:8888/admin/" + fileUUID;
        }
        //存储数据库
        Consumer sysFile = new Consumer();
        sysFile.setId(id);
        sysFile.setAvatar(url);
        sysFile.setMd5(md5);
        consumerMapper.updateById(sysFile);
        return url;
    }

    /**
     * 通过文件的md5查询文件
     *
     * @param md5
     * @return
     */
    private Consumer getFileByMd5(String md5) {
        //查询文件的md5是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Consumer> fileList = consumerMapper.selectList(queryWrapper);
        return fileList.size() == 0 ? null : fileList.get(0);
    }

    /**
     * 查询需要审批的用户
     *
     * @return
     */
    @GetMapping("/changeType")
    public R changeType(@RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<ConsumerDTO> page = consumerMapper.needConsumerType(new Page<>(pageNum, pageSize));
        return R.success("查询成功", page);
    }

    /**
     * 文件下载：下载路径 http://localhost:8888/admin/{fileUUID}
     * @param fileUUID
     * @param response
     * dccdd
     */

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath+fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");
        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

}
